/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */

export const RyListMixin = {
  data () {
    return {
      // 搜索条件框参数
      searchModelConfig: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18, offset: 0 }
      },
      searchRowConfig: {
        gutter: 24
      },
      searchColConfig: {
        span: 6
      },
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return ' 共 ' + total + ' 条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        hideOnSinglePage: false,
        total: 0,
        // pageSize 变化的回调
        onShowSizeChange: (current, pageSize) =>
          this.onShowSizeChange(current, pageSize),
        onChange: (page, pageSize) => this.pageChange(page, pageSize)
      },
      pages: 0,
      /* 排序参数 */
      orders: [{
        asc: false,
        column: 'create_time'
      }],
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      initQuery: true,
      reloadDict: false, // 是否刷新数据字典
      url: {
      }
    }
  },
  created () {

  },
  mounted () {
    if (this.initQuery) {
      this.loadData()
    }
  },
  computed: {
    // 禁用操作区修改
    disEdit () {
      return this.selectedRowKeys.length !== 1
    },
    // 禁用操作区删除
    disDelete () {
      return this.selectedRowKeys.length < 1
    }
  },
  methods: {
    loadData (arg) {
      // if (this.reloadDict) {
      //   this.$store.dispatch('GetDictData')
      // }
      if (!this.url.list) {
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      return new Promise((resolve, reject) => {
        this.$post(this.url.list, params).then(res => {
          if (this.isSuccess(res)) {
            this.dataSource = res.data.records || res.data.list || res.data
            this.ipagination.total = res.data.total
            this.pages = res.data.pages
            this.ipagination.current = Math.min(
              this.ipagination.current,
              Math.ceil(this.ipagination.total / this.ipagination.pageSize)
            )
            this.loading = false
            resolve(this.dataSource)
          }
          this.loading = false
        })
      })
    },
    // 分页size
    onShowSizeChange (current, pageSize) {
      this.ipagination.current = current
      this.ipagination.pageSize = pageSize
      this.loadData()
    },
    // 页码改变事件
    pageChange (page, pageSize) {
      this.ipagination.current = page
      this.loadData()
    },
    handleSuperQuery (params, matchType) {
      // 高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams () {
      // 获取查询条件
      let sqp = {}
      // if (this.superQueryParams) {
      //   sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      //   sqp['superQueryMatchType'] = this.superQueryMatchType
      // }
      const param = Object.assign(sqp, this.queryParam, this.filters, {
        orders: JSON.stringify(this.orders),
        current: this.ipagination.current,
        size: this.ipagination.pageSize
      })
      // param.field = this.getQueryField()
      return param // filterObj(param)
    },
    getQueryField () {
      // TODO 字段权限控制
      let str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    // 翻页多选，配合所有页全选方法使用
    onSelect (record, selected, selectedRows, nativeEvent) {
      if (selected) {
        this.selectedRowKeys.push(record.id)
        this.selectionRows.push(record)
      } else {
        this.selectedRowKeys = this.selectedRowKeys.filter(data => (data !== record.id))
        this.selectionRows = this.selectionRows.filter(data => (data.id !== record.id))
      }
    },
    // 所有页全选
    onSelectAll (selected, selectedRows, changeRows) {
      if (selected) {
        for (let i in changeRows) {
          let item = changeRows[i]
          this.selectedRowKeys.push(item.id)
          this.selectionRows.push(item)
        }
      } else {
        for (let i in changeRows) {
          let item = changeRows[i]
          this.selectedRowKeys = this.selectedRowKeys.filter(data => (data !== item.id))
          this.selectionRows = this.selectionRows.filter(data => (data.id !== item.id))
        }
      }
    },
    searchQuery () {
      this.loadData(1)
    },
    superQuery () {
      this.$refs.superQueryModal.show()
    },
    searchReset () {
      this.queryParam = {}
      this.loadData(1)
    },
    batchDel (afterHandle = () => { }) {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      }
      const that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function () {
          that.loading = true
          let param = that.selectedRowKeys
          that.$post(that.url.deleteBatch, param).then(res => {
            that.loading = false
            if (that.isSuccess(res)) {
              that.$message.success('删除成功')
              that.loadData(1)
              that.onClearSelected()
              if (afterHandle) {
                afterHandle()
              }
            }
          })
        }
      })
    },
    handleDelete (id, content = '所选数据', afterHandle = () => { }) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      let param = [id]
      this.$confirm({
        title: '确认删除',
        content: `是否确认删除${content}?`,
        onOk: () => {
          this.$post(this.url.delete, param).then(res => {
            if (this.isSuccess(res)) {
              this.$message.success('删除成功')
              this.loadData()
              this.onClearSelected()
              afterHandle()
            }
          })
        }
      })
    },
    handleEdit (record, modalName = 'modalForm') {
      this.$refs[modalName].edit(record)
      this.$refs[modalName].disableSubmit = false
    },
    handleAdd (e, record, modalName = 'modalForm') {
      this.$refs[modalName].add(record)
      this.$refs[modalName].disableSubmit = false
    },
    handleView (record, modalName = 'modalForm') {
      this.$refs[modalName].view(record)
      this.$refs[modalName].disableSubmit = false
    },
    handleAddDef (id, modalName = 'modalForm') {
      this.$refs[modalName].add(id)
      this.$refs[modalName].disableSubmit = false
    },
    handleUpload (acceptType, modalName = 'modalForm') {
      this.$refs[modalName].upload(acceptType)
    },
    handleTableChange (pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.orderByColumn = sorter.field
        this.isorter.isAsc = sorter.order === 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleToggleSearch () {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    modalFormOk () {
      // 新增/修改 成功时，重载列表
      this.loadData(1)
      this.onClearSelected()
    },
    handleDetail (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.disableSubmit = true
    },
    /* 导入 */
    handleImportExcel (info) {
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (this.isSuccess(info.file.response)) {
          if (info.file.response.code === 201) { } else {
            this.$message.success(
              info.file.response.msg || `${info.file.name} 文件上传成功`
            )
            typeof this.importCallback === 'function' &&
              this.importCallback(info.file, info.file.response)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.msg}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    }
  }
}
